package io.gitee.caoxiaoyu97.log4j.defender.matcher;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.springframework.util.StringUtils;

public class StringKeyMatcher
        implements KeyMatcher {
    private static Set<String> originKeys = new HashSet<>();
    private Pattern invalidKeyPattern = Pattern.compile(".*(\"|,|\\[|\\]|\\{|\\}|\\s|\\\\)+.*");

    public StringKeyMatcher(String keys) {
        String[] keyArray = StringUtils.isEmpty(keys) ? new String[0] : keys.split(",");
        originKeys.addAll((Collection<? extends String>) Arrays.<String>stream(keyArray).filter(it -> !isInValidKey(it)).collect(Collectors.toSet()));
    }


    protected boolean isInValidKey(String input) {
        try {
            return (StringUtils.isEmpty(input) || this.invalidKeyPattern.matcher(input.trim()).matches());
        } catch (Exception e) {
            return true;
        }
    }


    public Set<String> getOriginKeys() {
        return originKeys;
    }
}
